package es.xpt.ysf.commons.changelogger;

import static javax.ejb.TransactionAttributeType.REQUIRED;

import java.util.List;

import javax.annotation.Resource;
import javax.ejb.Asynchronous;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;

import org.apache.commons.lang.NotImplementedException;

import es.xpt.ysf.YSFException;
import es.xpt.ysf.commons.changelogger.model.Change;
import es.xpt.ysf.commons.changelogger.model.ChangeSearchParams;
import es.xpt.ysf.jaas.YSFPrincipal;
import es.xpt.ysf.logging.LogManager;


@TransactionAttribute(REQUIRED)
@Stateless(name = "ChangeLoggerSession")
public class ChangeLoggerSessionBean implements ChangeLoggerSession {
	
	@Resource
	private SessionContext context;

	@TransactionAttribute(TransactionAttributeType.NEVER)
	@Asynchronous
	public void logChanges(List<Change> changeList, String logTable) throws YSFException {
		
		
		ChangeLoggerDAOFactory f = null;
		try {
			f = new ChangeLoggerDAOFactory(((YSFPrincipal)context.getCallerPrincipal()).getBigData(),context.getCallerPrincipal());
			f.getChangeLoggerDAO().insertChanges(changeList, logTable);
		} catch ( Throwable t ) {
			LogManager.getLog(getClass()).error("changeLogger:" + t.getMessage(), t);
		} finally {
			if (f != null)
				f.release();
		}
		
	}

	@Override
	public List<Change> searchChanges(ChangeSearchParams search) throws YSFException {
		// TODO: Implement this!!
		throw new NotImplementedException();
	}
}